<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="js," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="一直想总结一篇js的字符串操作文档，之前有过笔记，但是都比较零散，而且es6的出现让操作字符串出现了一些新的方式，今天看到了《JavaScript 字符串实用常操纪要》这篇blog，感觉总结的比较全面、实用特此摘抄一下。我自己常用到的方法加了强调符号。 字符串截取1. substring()1xString.substring(start,end)  substring()是最常用到的字符串截取方">
<meta name="keywords" content="js">
<meta property="og:type" content="article">
<meta property="og:title" content="js字符串操作">
<meta property="og:url" content="http://lanbos.win/2016/12/01/FE/js_stringHandle/index.html">
<meta property="og:site_name" content="lanbos&#39;blog">
<meta property="og:description" content="一直想总结一篇js的字符串操作文档，之前有过笔记，但是都比较零散，而且es6的出现让操作字符串出现了一些新的方式，今天看到了《JavaScript 字符串实用常操纪要》这篇blog，感觉总结的比较全面、实用特此摘抄一下。我自己常用到的方法加了强调符号。 字符串截取1. substring()1xString.substring(start,end)  substring()是最常用到的字符串截取方">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2016-12-01T03:22:56.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="js字符串操作">
<meta name="twitter:description" content="一直想总结一篇js的字符串操作文档，之前有过笔记，但是都比较零散，而且es6的出现让操作字符串出现了一些新的方式，今天看到了《JavaScript 字符串实用常操纪要》这篇blog，感觉总结的比较全面、实用特此摘抄一下。我自己常用到的方法加了强调符号。 字符串截取1. substring()1xString.substring(start,end)  substring()是最常用到的字符串截取方">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://lanbos.win/2016/12/01/FE/js_stringHandle/"/>





  <title> js字符串操作 | lanbos'blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">lanbos'blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">这个人假装很懒，什么都没有留下</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://lanbos.win/2016/12/01/FE/js_stringHandle/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="lanbos">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="https://ws1.sinaimg.cn/large/5c9d16d6gw1fbesf3zrhej209p09ftai.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="lanbos'blog">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="lanbos'blog" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                js字符串操作
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2016-12-01T09:48:40+08:00">
                2016-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/coder/" itemprop="url" rel="index">
                    <span itemprop="name">码畜相关</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>一直想总结一篇js的字符串操作文档，之前有过笔记，但是都比较零散，而且<code>es6</code>的出现让操作字符串出现了一些新的方式，今天看到了<a href="http://www.jeffjade.com/2016/11/24/116-JavaScript-string-operation/" target="_blank" rel="external">《JavaScript 字符串实用常操纪要》</a>这篇blog，感觉总结的比较全面、实用特此摘抄一下。我自己常用到的方法加了强调符号。</p>
<h2 id="字符串截取"><a href="#字符串截取" class="headerlink" title="字符串截取"></a>字符串截取</h2><h3 id="1-substring"><a href="#1-substring" class="headerlink" title="1. substring()"></a>1. substring()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">xString.substring(start,end)</div></pre></td></tr></table></figure>
<blockquote>
<p>substring()是最常用到的字符串截取方法，它可以接收两个参数(参数不能为负值)，分别是要截取的开始位置和结束位置，它将返回一个新的字符串，其内容是从start处到end-1处的所有字符。若结束参数(end)省略，则表示从start位置一直截取到最后。</p>
</blockquote>
<a id="more"></a>
<p>举例：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(str.substring(<span class="number">0</span>,<span class="number">3</span>)) <span class="comment">// www</span></div><div class="line"><span class="built_in">console</span>.log(str.substring(<span class="number">0</span>))   <span class="comment">//www.jeffjade.com</span></div><div class="line"><span class="built_in">console</span>.log(str.substring(<span class="number">-2</span>))  <span class="comment">//www.jeffjade.com (传负值则视为0)</span></div></pre></td></tr></table></figure></p>
<h3 id="2-slice"><a href="#2-slice" class="headerlink" title="2. slice()"></a>2. <em>slice()</em></h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">stringObject.slice(start, end)</div></pre></td></tr></table></figure>
<blockquote>
<p>slice()方法与substring()方法非常类似，它传入的两个参数也分别对应着开始位置和结束位置。而区别在于，slice()中的参数可以为负值，如果参数是负数，则该参数规定的是从字符串的尾部开始算起的位置。也就是说，-1 指字符串的最后一个字符。</p>
</blockquote>
<p>举例：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(str.slice(<span class="number">0</span>, <span class="number">3</span>))    <span class="comment">// www</span></div><div class="line"><span class="built_in">console</span>.log(str.slice(<span class="number">-3</span>, <span class="number">-1</span>))  <span class="comment">// co</span></div><div class="line"><span class="built_in">console</span>.log(str.slice(<span class="number">1</span>, <span class="number">-1</span>))   <span class="comment">// www.jeffjade.co</span></div><div class="line"><span class="built_in">console</span>.log(str.slice(<span class="number">2</span>, <span class="number">1</span>))    <span class="comment">// '' (返回空字符串,start须小于end)</span></div><div class="line"><span class="built_in">console</span>.log(str.slice(<span class="number">-3</span>, <span class="number">0</span>))   <span class="comment">// '' (返回空字符串,start须小于end)</span></div></pre></td></tr></table></figure></p>
<h3 id="3-substr"><a href="#3-substr" class="headerlink" title="3. substr()"></a>3. substr()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">stringObject.substr(start,length)</div></pre></td></tr></table></figure>
<blockquote>
<p>substr()方法可在字符串中抽取从start下标开始的指定数目的字符。其返回值为一个字符串，包含从 stringObject的start（包括start所指的字符）处开始的length个字符。如果没有指定 length，那么返回的字符串包含从start到stringObject的结尾的字符。另外如果start为负数，则表示从字符串尾部开始算起</p>
</blockquote>
<p>举例：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(webStr.substr(<span class="number">1</span>, <span class="number">3</span>))   <span class="comment">// ww.</span></div><div class="line"><span class="built_in">console</span>.log(webStr.substr(<span class="number">0</span>))      <span class="comment">// www.jeffjade.com</span></div><div class="line"><span class="built_in">console</span>.log(webStr.substr(<span class="number">-3</span>, <span class="number">3</span>))  <span class="comment">// com</span></div><div class="line"><span class="built_in">console</span>.log(webStr.substr(<span class="number">-1</span>, <span class="number">5</span>))  <span class="comment">// m  (目标长度较大的话，以实际截取的长度为准)</span></div></pre></td></tr></table></figure></p>
<h3 id="4-split"><a href="#4-split" class="headerlink" title="4. split()"></a>4. <em>split()</em></h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">str.split([separator][, limit])</div></pre></td></tr></table></figure>
<blockquote>
<ul>
<li>separator 指定用来分割字符串的字符（串）。separator 可以是一个字符串或正则表达式。 如果忽略 separator，则返回整个字符串的数组形式。如果 separator 是一个空字符串，则 str 将会把原字符串中每个字符的数组形式返回。</li>
<li>limit 一个整数，限定返回的分割片段数量。split 方法仍然分割每一个匹配的 separator，但是返回的数组只会截取最多 limit 个元素。</li>
</ul>
</blockquote>
<p>举例：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line">str.split(<span class="string">'.'</span>)      <span class="comment">// ["www", "jeffjade", "com"]</span></div><div class="line">str.split(<span class="string">'.'</span>, <span class="number">1</span>)   <span class="comment">// ["www"]</span></div><div class="line">str.split(<span class="string">'.'</span>).join(<span class="string">''</span>) <span class="comment">// wwwjeffjadecom</span></div></pre></td></tr></table></figure></p>
<p>原文作者对这个方法比较称道，我自己也很常用这个方法，<code>splite()</code>和<code>join()</code>配合使用是很常见的方式。</p>
<h2 id="查找类方法"><a href="#查找类方法" class="headerlink" title="查找类方法"></a>查找类方法</h2><h3 id="1-indexOf-amp-includes"><a href="#1-indexOf-amp-includes" class="headerlink" title="1.  indexOf() &amp; includes()"></a>1.  <em>indexOf()</em> &amp; includes()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">stringObject.indexOf(searchValue,fromIndex)</div></pre></td></tr></table></figure>
<blockquote>
<p>indexOf()用来检索指定的字符串值在字符串中首次出现的位置。它可以接收两个参数，searchValue 表示要查找的子字符串，fromIndex 表示查找的开始位置，省略的话则从开始位置进行检索。</p>
</blockquote>
<p>举例<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(str.indexOf(<span class="string">'.'</span>))     <span class="comment">// 3</span></div><div class="line"><span class="built_in">console</span>.log(str.indexOf(<span class="string">'.'</span>, <span class="number">1</span>))  <span class="comment">// 3</span></div><div class="line"><span class="built_in">console</span>.log(str.indexOf(<span class="string">'.'</span>, <span class="number">5</span>))  <span class="comment">// 12</span></div><div class="line"><span class="built_in">console</span>.log(str.indexOf(<span class="string">'.'</span>, <span class="number">12</span>)) <span class="comment">// -1</span></div></pre></td></tr></table></figure></p>
<p>虽然 indexOf()用来检索指定的字符串值在字符串中首次出现的位置 ，然而很多时候，使用它的场景在于判断字符串中是否存在指定的字符串；因此代码就会如此：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (str.indexOf(<span class="string">'yoursPecifiedStr'</span>) !== <span class="number">-1</span>) &#123;</div><div class="line">    <span class="comment">// do something</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>要知道在这样的场景下，<code>ES6</code> 语言中的includes()就显得更优雅许多；includes() 方法用于判断一个字符串是否被包含在另一个字符串中，如果是返回true，否则返回false。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">str.includes(searchString[, position])</div></pre></td></tr></table></figure></p>
<blockquote>
<p>searchString 将要搜寻的子字符串。position 可选。从当前字符串的哪个索引位置开始搜寻子字符串；默认为0。需要注意的是，includes() 是区分大小写的。</p>
</blockquote>
<p>举例<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="string">'Blue Whale'</span>.includes(<span class="string">'blue'</span>); <span class="comment">// returns false</span></div><div class="line"><span class="string">'乔峰乔布斯乔帮主'</span>.includes(<span class="string">'乔布斯'</span>); <span class="comment">// returns true</span></div><div class="line"><span class="keyword">if</span> (str.includes(<span class="string">'yoursPecifiedStr'</span>)) &#123;</div><div class="line">    <span class="comment">// do something(这样写是不是更为人性化？Yeah，这是一个更趋向人性化的时代嘛)</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="2-lastIndexOf"><a href="#2-lastIndexOf" class="headerlink" title="2. lastIndexOf()"></a>2. lastIndexOf()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">stringObject.lastIndexOf(searchValue,fromIndex)</div></pre></td></tr></table></figure>
<blockquote>
<p>lastIndexOf()语法与indexOf()类似，它返回的是一个指定的子字符串值最后出现的位置，其检索顺序是从后向前。</p>
</blockquote>
<p>举例<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(str.lastIndexOf(<span class="string">'.'</span>))     <span class="comment">// 12</span></div><div class="line"><span class="built_in">console</span>.log(str.lastIndexOf(<span class="string">'.'</span>, <span class="number">1</span>))  <span class="comment">// -1</span></div><div class="line"><span class="built_in">console</span>.log(str.lastIndexOf(<span class="string">'.'</span>, <span class="number">5</span>))  <span class="comment">// 3</span></div><div class="line"><span class="built_in">console</span>.log(str.lastIndexOf(<span class="string">'.'</span>, <span class="number">12</span>)) <span class="comment">// 12</span></div></pre></td></tr></table></figure></p>
<h3 id="3-search"><a href="#3-search" class="headerlink" title="3.search()"></a>3.search()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">stringObject.search(substr)</div><div class="line">stringObject.search(regexp)</div></pre></td></tr></table></figure>
<blockquote>
<p>search()方法用于检索字符串中指定的子字符串，或检索与正则表达式相匹配的子字符串。它会返回第一个匹配的子字符串的起始位置，如果没有匹配的，则返回-1</p>
</blockquote>
<p>举例<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(str.search(<span class="string">'w'</span>))    <span class="comment">// 0</span></div><div class="line"><span class="built_in">console</span>.log(str.search(<span class="regexp">/j/g</span>))   <span class="comment">// 4</span></div><div class="line"><span class="built_in">console</span>.log(str.search(<span class="regexp">/\./g</span>))  <span class="comment">// 3</span></div></pre></td></tr></table></figure></p>
<h3 id="3-match"><a href="#3-match" class="headerlink" title="3.match()"></a>3.match()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">stringObject.match(substr)</div><div class="line">stringObject.match(regexp)</div></pre></td></tr></table></figure>
<blockquote>
<p>match()方法可在字符串内检索指定的值，或找到一个或多个正则表达式的匹配。<br>如果参数中传入的是子字符串或是没有进行全局匹配的正则表达式，那么match()方法会从开始位置执行一次匹配，如果没有匹配到结果，则返回null。否则则会返回一个数组，该数组的第0个元素存放的是匹配文本，除此之外，返回的数组还含有两个对象属性index和input，分别表示匹配文本的起始字符索引和stringObject 的引用(即原字符串)。</p>
</blockquote>
<p>举例<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'#1a2b3c4d5e#'</span>;</div><div class="line"><span class="built_in">console</span>.log(str.match(<span class="string">'A'</span>));    <span class="comment">//返回null</span></div><div class="line"><span class="built_in">console</span>.log(str.match(<span class="string">'b'</span>));    <span class="comment">//返回["b", index: 4, input: "#1a2b3c4d5e#"]</span></div><div class="line"><span class="built_in">console</span>.log(str.match(<span class="regexp">/b/</span>));    <span class="comment">//返回["b", index: 4, input: "#1a2b3c4d5e#"]</span></div></pre></td></tr></table></figure></p>
<blockquote>
<p>如果参数传入的是具有全局匹配的正则表达式，那么match()从开始位置进行多次匹配，直到最后。如果没有匹配到结果，则返回null。否则则会返回一个数组，数组中存放所有符合要求的子字符串，并且没有index和input属性。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'#1a2b3c4d5e#'</span></div><div class="line"><span class="built_in">console</span>.log(str.match(<span class="regexp">/h/g</span>))     <span class="comment">//返回null</span></div><div class="line"><span class="built_in">console</span>.log(str.match(<span class="regexp">/\d/g</span>))    <span class="comment">//返回["1", "2", "3", "4", "5"]</span></div></pre></td></tr></table></figure>
<h2 id="其他方法"><a href="#其他方法" class="headerlink" title="其他方法"></a>其他方法</h2><h3 id="1-replace"><a href="#1-replace" class="headerlink" title="1.replace()"></a>1.<em>replace()</em></h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">stringObject.replace(regexp/substr,replacement)</div></pre></td></tr></table></figure>
<blockquote>
<p>replace()方法用来进行字符串替换操作，它可以接收两个参数，前者为被替换的子字符串（可以是正则），后者为用来替换的文本。<br>如果第一个参数传入的是子字符串或是没有进行全局匹配的正则表达式，那么replace()方法将只进行一次替换（即替换最前面的），返回经过一次替换后的结果字符串。</p>
</blockquote>
<p>举例<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(str.replace(<span class="string">'w'</span>, <span class="string">'W'</span>))   <span class="comment">// Www.jeffjade.com</span></div><div class="line"><span class="built_in">console</span>.log(str.replace(<span class="regexp">/w/</span>, <span class="string">'W'</span>))   <span class="comment">// Www.jeffjade.com</span></div></pre></td></tr></table></figure></p>
<blockquote>
<p>如果第一个参数传入的全局匹配的正则表达式，那么replace()将会对符合条件的子字符串进行多次替换，最后返回经过多次替换的结果字符串。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(str.replace(<span class="regexp">/w/g</span>, <span class="string">'W'</span>))   <span class="comment">// WWW.jeffjade.com</span></div></pre></td></tr></table></figure></p>
</blockquote>
<h3 id="2-toLowerCase-amp-toUpperCase"><a href="#2-toLowerCase-amp-toUpperCase" class="headerlink" title="2.toLowerCase() &amp; toUpperCase()"></a>2.toLowerCase() &amp; toUpperCase()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">stringObject.toLowerCase()</div><div class="line">stringObject.toUpperCase()</div></pre></td></tr></table></figure>
<blockquote>
<p>toLowerCase()方法可以把字符串中的大写字母转换为小写，toUpperCase()方法可以把字符串中的小写字母转换为大写。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> str = <span class="string">'www.jeffjade.com'</span></div><div class="line"><span class="built_in">console</span>.log(str.toLowerCase())   <span class="comment">// www.jeffjade.com</span></div><div class="line"><span class="built_in">console</span>.log(str.toUpperCase())   <span class="comment">// WWW.JEFFJADE.COM</span></div></pre></td></tr></table></figure>
<h3 id="3-模板字符串"><a href="#3-模板字符串" class="headerlink" title="3.模板字符串"></a>3.模板字符串</h3><p>这是<code>es6</code>的新特性，的确比较人性化，感觉是借鉴了类似于python等语言的理念</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">ncieFunc</span>(<span class="params"></span>) </span>&#123;</div><div class="line">  <span class="keyword">return</span> <span class="string">"四海无人对夕阳"</span>;</div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> niceMan = <span class="string">"陈寅恪"</span>;</div><div class="line"><span class="keyword">var</span> jadeTalk = <span class="string">`一生负气成今日 \n <span class="subst">$&#123;ncieFunc()&#125;</span> ,</span></div><div class="line">语出 <span class="subst">$&#123;niceMan&#125;</span> 的《忆故居》。</div><div class="line">`</div><div class="line"><span class="built_in">console</span>.log(jadeTalk)</div></pre></td></tr></table></figure>
<p>运行结果如下：</p>
<blockquote>
<p>一生负气成今日<br>四海无人对夕阳 ,<br>语出 陈寅恪 的《忆故居》。</p>
</blockquote>
<h2 id="配合使用"><a href="#配合使用" class="headerlink" title="配合使用"></a>配合使用</h2><p>很多字符串的操作可以自定义工具函数来进行使用，<code>lodash</code>和<code>jquery</code>中提供了很多，这里摘抄原blog的一些使用。</p>
<h3 id="1-字符串反转"><a href="#1-字符串反转" class="headerlink" title="1.字符串反转"></a>1.字符串反转</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">String</span>.prototype.reverse = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">	<span class="keyword">return</span> <span class="keyword">this</span>.split(<span class="string">''</span>).reverse().join(<span class="string">''</span>)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="2-去除空白行"><a href="#2-去除空白行" class="headerlink" title="2.去除空白行"></a>2.去除空白行</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">String</span>.prototype.removeBlankLines = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">	<span class="keyword">return</span> <span class="keyword">this</span>.replace(<span class="regexp">/(\n[\s\t]*\r*\n)/g</span>, <span class="string">'\n'</span>).replace(<span class="regexp">/^[\n\r\n\t]*|[\n\r\n\t]*$/g</span>, <span class="string">''</span>)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><em>去除字符串两端的空格可以用原生方法trim()</em></p>
<h3 id="3-转化为二维数组"><a href="#3-转化为二维数组" class="headerlink" title="3.转化为二维数组"></a>3.转化为二维数组</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">String</span>.prototype.removeBlankLines = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">	<span class="keyword">return</span> <span class="keyword">this</span>.replace(<span class="regexp">/(\n[\s\t]*\r*\n)/g</span>, <span class="string">'\n'</span>).replace(<span class="regexp">/^[\n\r\n\t]*|[\n\r\n\t]*$/g</span>, <span class="string">''</span>)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="built_in">String</span>.prototype.strTo2dArr = <span class="function"><span class="keyword">function</span>(<span class="params">firstSplit, secondSplit</span>)</span>&#123;</div><div class="line">	<span class="keyword">var</span> contentStr = <span class="keyword">this</span>.removeBlankLines(),</div><div class="line">		contentStrArr = contentStr.split(firstSplit),</div><div class="line">		resultArr = contentStrArr.map(<span class="function">(<span class="params">element</span>) =&gt;</span> &#123;</div><div class="line">            <span class="keyword">return</span> element.split(secondSplit)</div><div class="line">        &#125;)</div><div class="line">	<span class="keyword">return</span> resultArr</div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> str = <span class="string">`</span></div><div class="line">渺渺钟声出远方,依依林影万鸦藏。</div><div class="line">一生负气成今日,四海无人对夕阳。</div><div class="line">破碎山河迎胜利,残馀岁月送凄凉。</div><div class="line">松门松菊何年梦,且认他乡作故乡。</div><div class="line">`</div><div class="line"><span class="built_in">console</span>.log(str.strTo2dArr(<span class="string">'\n'</span>, <span class="string">','</span>))</div></pre></td></tr></table></figure>
<p>运行结果为</p>
<blockquote>
<p>[ [ ‘渺渺钟声出远方’, ‘依依林影万鸦藏。’ ],<br>[ ‘一生负气成今日’, ‘四海无人对夕阳。’ ],<br>[ ‘破碎山河迎胜利’, ‘残馀岁月送凄凉。’ ],<br>[ ‘松门松菊何年梦’, ‘且认他乡作故乡。’ ] ]</p>
</blockquote>
<p><em>直接转化为数组用split</em></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js/" rel="tag"># js</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/11/23/hexo/hexo_others/" rel="next" title="hexo其他问题">
                <i class="fa fa-chevron-left"></i> hexo其他问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/12/28/FE/readingNotes1/" rel="prev" title="《移动网页设计与开发html5+css3+javascript》读书笔记">
                《移动网页设计与开发html5+css3+javascript》读书笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>
  <!-- UY BEGIN -->
<div id="uyan_frame"></div>
<script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2123221"></script>
<!-- UY END -->



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://ws1.sinaimg.cn/large/5c9d16d6gw1fbesf3zrhej209p09ftai.jpg"
               alt="lanbos" />
          <p class="site-author-name" itemprop="name">lanbos</p>
          <p class="site-description motion-element" itemprop="description">这个人假装很懒，什么都没有留下</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">24</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">16</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#字符串截取"><span class="nav-number">1.</span> <span class="nav-text">字符串截取</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-substring"><span class="nav-number">1.1.</span> <span class="nav-text">1. substring()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-slice"><span class="nav-number">1.2.</span> <span class="nav-text">2. slice()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-substr"><span class="nav-number">1.3.</span> <span class="nav-text">3. substr()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-split"><span class="nav-number">1.4.</span> <span class="nav-text">4. split()</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查找类方法"><span class="nav-number">2.</span> <span class="nav-text">查找类方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-indexOf-amp-includes"><span class="nav-number">2.1.</span> <span class="nav-text">1.  indexOf() & includes()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-lastIndexOf"><span class="nav-number">2.2.</span> <span class="nav-text">2. lastIndexOf()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-search"><span class="nav-number">2.3.</span> <span class="nav-text">3.search()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-match"><span class="nav-number">2.4.</span> <span class="nav-text">3.match()</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他方法"><span class="nav-number">3.</span> <span class="nav-text">其他方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-replace"><span class="nav-number">3.1.</span> <span class="nav-text">1.replace()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-toLowerCase-amp-toUpperCase"><span class="nav-number">3.2.</span> <span class="nav-text">2.toLowerCase() & toUpperCase()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-模板字符串"><span class="nav-number">3.3.</span> <span class="nav-text">3.模板字符串</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配合使用"><span class="nav-number">4.</span> <span class="nav-text">配合使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-字符串反转"><span class="nav-number">4.1.</span> <span class="nav-text">1.字符串反转</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-去除空白行"><span class="nav-number">4.2.</span> <span class="nav-text">2.去除空白行</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-转化为二维数组"><span class="nav-number">4.3.</span> <span class="nav-text">3.转化为二维数组</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lanbos</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  

  

  

  

  


</body>
</html>
